import { Component, ViewChild } from '@angular/core';
import { Router, ActivatedRoute, ActivationEnd } from '@angular/router';
import { TabsComponent } from '../tabs/tabs.component';
import { Title } from '@angular/platform-browser';
import { filter } from 'rxjs/operators';
import { NzModalService } from 'ng-zorro-antd/modal';
import { CustomReuseStrategy } from './customreusestrategy'
import { trigger, state, style, transition, animate } from '@angular/animations';
import { PersonInfoComponent } from '../logininfo/personinfo.component'
import { UpdatepwdComponent } from '../logininfo/updatepwd.component'

import { LocalStorage } from '../../utils/localstorage';
import { HttpService } from "../../http/http.service";
import { MetaModalService } from "../meta/meta-modal/meta-modal.service";


@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: [ './main.component.styl' ],
  providers: [ CustomReuseStrategy ],
  animations: [
    trigger('myanimation', [
      state('show', style({
        transform: 'translateX(0px)'
      })),
      state('hide', style({
        transform: 'translateX(-200px)'
      })),
      transition('show <=> hide', animate('500ms ease-in'))
    ])
  ]
})

export class MainComponent {

  menus: any = [];

  isGender: Boolean = true;//true=男，false=女

  isCollapsed = false;

  currUserName: string = "";

  state: string = "show";

  headerHidden = false;// 控制显示影藏header

  @ViewChild('tabs', { static: true }) tabs: TabsComponent;
  @ViewChild('updatepwd', { static: false }) updatepwd: UpdatepwdComponent;

  constructor(
    private router: Router,// 路由器控制器
    private activatedRoute: ActivatedRoute,// 当前组件相关的路由器
    private titleService: Title,
    private modalService: NzModalService,
    private http: HttpService,
    private metaModalService: MetaModalService,
  ) {
    this.router.events.pipe(filter(e => e instanceof ActivationEnd))
      .subscribe((e: ActivationEnd) => {
        const snapshot = e.snapshot;
        const name = snapshot.routeConfig.path;

        if (name === "login") {
          return;
        }

        if (name === "home") {
          this.setPageTitle("首页");
          return;
        }
        if(!(this.menus && this.menus.length>0)) {
          let tempMenus = window.menus;
          if(!tempMenus){
            return;
          }
          this.setMenuVal(tempMenus);
          this.menus = tempMenus;
        }
        this.queryMenus(this.menus, name);
      });

    let info: any = LocalStorage.getInfoObject();
    if(info) {
      this.currUserName = info.userName;
      this.isGender = info.gender !== "1";//0=男，1=女
    }
  }

  setPageTitle(title: string) {
    this.titleService.setTitle("爱波瑞精益制造测评系统-" + title);
  }

  onSwitchMenu() {
    this.state = this.state == 'show' ? 'hide' : 'show';
  }

  onSwitchStart(event: AnimationEvent) {
    if (this.state == 'show') {
      this.isCollapsed = false;
    }
  }

  onSwitchEnd(event: AnimationEvent) {
    if (this.state == 'hide') {
      this.isCollapsed = true;
    }
  }

  onTabClick(tab) {
    this.setPageTitle(tab.text);
    let aryPath = this.setPathArray(tab.path);
    this.router.navigate(aryPath, { relativeTo: this.activatedRoute }).finally();
  }

  onCloseTab(tabInfo) {
    this.setPageTitle(tabInfo.curTab.text);
    let aryPath = this.setPathArray(tabInfo.curTab.path);
    this.router.navigate(aryPath, { relativeTo: this.activatedRoute }).then(() => {
      CustomReuseStrategy.deleteRouteSnapshot('/wel/' + tabInfo.delTab.path);
    });
  }

  setPathArray(path: string): string[] {
    let aryPath: string[] = (path).split("/");
    return aryPath;
  }

  onDisTabSet(hidden) {
    this.headerHidden = hidden;
    this.state = hidden ? 'hide' : 'show';
  }

  openPerson;
  onOpenPersonInfo() {
    this.openPerson =this.metaModalService.create({
      nzTitle: '个人基本信息',
      nzStyle: { top: '20px' },
      nzWidth: 800,
      nzContent: PersonInfoComponent,
      nzComponentParams: {
        parent: this
      },
    });
  }
  modalPwd;
  onOpenPwd() {
    this.modalPwd = this.metaModalService.create({
      nzTitle: '修改密码',
      nzWidth: 500,
      nzContent: UpdatepwdComponent,
      nzComponentParams: {
        parent: this
      },
    });
  }

  onExit() {
    this.modalService.confirm({
      nzTitle: '<i>提示</i>',
      nzContent: '<b>确定要退出系统吗?</b>',
      nzOnOk: () => {
        CustomReuseStrategy.deleteALLRouteSnapshot();
        this.goLoginUrl();
      }
    });
  }

  goLoginUrl() {
    LocalStorage.removeToken();
    this.router.navigate([ '/', 'login' ]);
  }

  setMenuVal(menus: any, level: number = 1) {
    for (let i = 0; i < menus.length; i++) {
      let menu = menus[i];

      menu.open = false;
      menu.level = level;

      if (menu.children && menu.children.length > 0) {
        this.setMenuVal(menu.children, level + 1);
      }
    }
  }

  queryMenus(menus: any, currName: string): boolean {
    for (let i = 0; i < menus.length; i++) {
      let menu = menus[i];

      if (currName === menu.name) {
        if (!menu.children || menu.children.length <= 0) {
          this.tabs.newTab(menu);
          this.setPageTitle(menu.text);
        }
        return false;

      }
      if (menu.children && menu.children.length > 0) {
        let ret: boolean = this.queryMenus(menu.children, currName);
        if (!ret) {
          return false;
        }
      }
    }
    return true;
  }
}
